<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { FormType } from './index'
import { GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/signintask'
import { GetOptionList } from '@/api/modules/subscribermsgtemple'
import { GetOptionData } from '@/api/modules/voucher'
import detailStore from '@/store/modules/NewCacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const id = route.query.id as string

const optionList = reactive({
  subscribermsgtempleOption: [],
  couponOption: [],
})
const taskTypeObj: { [key: number]: string } = {
  1: '连续签到送券',
  2: '邀请好友签到',
  // 3: '加福利管企微好友',
  // 4: '订阅消息提醒',
}
const ruleFormRef = ref<FormInstance>()
const ruleForm: any = ref<FormType>({
  taskType: 1,
  pic: '',
  title: '',
  taskDesp: '',
  awardDesp: '',
  awardScore: 0,
  signDays: 1,
  ticketId: 0,
  linkUrl: '',
  qvcodePic: '',
  templateIds: '',
  taskStatus: -1,
  sort: 0,
  enable: 1,
})

const rules = reactive({
  awardDesp: [
    { required: true, message: '请输入奖励描述', trigger: 'blur' },
  ],
  pic: [
    { required: true, message: '请上传任务图标', trigger: 'blur' },
  ],
  taskDesp: [
    { required: true, message: '请输入任务描述', trigger: 'blur' },
  ],
  title: [
    { required: true, message: '请输入任务标题', trigger: 'blur' },
  ],
})

// 图片上传赋值
function handleUploadSuccess(url: string, key: string) {
  ruleForm.value[key] = url
}

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const params = {
        ...ruleForm.value,
      }
      if (params.taskType === 2 || params.taskType === '2') {
        params.ticketId = 0
        params.signdays = 0
      }
      if (params.taskType === 4 || params.taskType === '4') {
        params.templateIds = params.templateIds.join(',')
      }
      if (id) {
        // 编辑
        params.id = id
        PutModifyData(ruleForm.value).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('编辑成功')
            router.push({ name: 'signintaskIndex' })
          }
          else {
            if (typeof res.errors === 'string') {
              ElMessage.error(`编辑失败。${res.errors}`)
            }
            else {
              let errorStr = ''
              for (const key in res.errors) {
                errorStr += `${key}：${res.errors[key]}；`
              }
              ElMessage.error(`编辑失败。${errorStr}`)
            }
          }
        })
      }
      else {
        // 添加
        PostCreateData(ruleForm.value).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.emptyFormData('signintaskForm')
            router.push({ name: 'signintaskIndex' })
          }
          else {
            if (typeof res.errors === 'string') {
              ElMessage.error(`添加失败。${res.errors}`)
            }
            else {
              let errorStr = ''
              for (const key in res.errors) {
                errorStr += `${key}：${res.errors[key]}；`
              }
              ElMessage.error(`添加失败。${errorStr}`)
            }
          }
        })
      }
    }
  })
}

onMounted(async () => {
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
        ruleForm.value.taskType = String(ruleForm.value.taskType)
      }
    })
  }
  else {
    ruleForm.value = detailData.getFormData('signintaskForm')
  }
  if (ruleForm.value.taskType === '4') {
    ruleForm.value.templateIds = ruleForm.value.templateIds.split(',')
  }
  watch(ruleForm, (newValue) => {
    if (!id) {
      detailData.rememberFormData('signintaskForm', newValue)
    }
  }, { deep: true })

  // 获取订阅消息模板的选项
  GetOptionList().then((res: any) => {
    if (res.succeeded) {
      optionList.subscribermsgtempleOption = res.data
    }
  })
  // 获取优惠券的选项
  GetOptionData().then((res: any) => {
    if (res.succeeded) {
      optionList.couponOption = res.data
    }
  })
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" :rules="rules" label-width="80px" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="任务标题" prop="title">
              <el-input v-model="ruleForm.title" placeholder="请输入任务标题" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="任务类型">
              <el-select v-model="ruleForm.taskType" placeholder="请选择" clearable>
                <el-option v-for="(item, key) in taskTypeObj" :key="key" :label="item" :value="key" />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="任务状态">
              <el-switch
                v-model="ruleForm.taskStatus"
                :active-value="1"
                :inactive-value="-1"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="排序（升序）">
              <el-input v-model="ruleForm.sort" placeholder="请输入排序" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="奖励积分">
              <el-input v-model="ruleForm.awardScore" placeholder="请输入奖励积分" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="跳转路径">
              <el-input v-model="ruleForm.linkUrl" placeholder="请输入跳转路径" />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.taskType === '1'" :md="12">
            <ElFormItem label="绑定券">
              <el-select v-model="ruleForm.ticketId" placeholder="请选择券" clearable filterable style="max-width: 350px;">
                <el-option v-for="item in (optionList.couponOption as any)" :key="item.id" :label="`${item.id}-${item.name}`" :value="item.id" />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.taskType === '1'" :md="8">
            <ElFormItem label="连续签到天数">
              <el-input-number v-model="ruleForm.signDays" placeholder="请输入连续签到天数" :min="1" :max="7" />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.taskType === '4' || ruleForm.taskType === '2'" :md="24">
            <ElFormItem v-if="ruleForm.taskType === '4'" label="绑定模板">
              <el-select v-model="ruleForm.templateIds" placeholder="请选择" clearable multiple style="max-width: 600px;">
                <el-option v-for="item in (optionList.subscribermsgtempleOption as any)" :key="item.dingyueTemplateId" :label="item.wxTemplateTitle" :value="item.dingyueTemplateId" />
              </el-select>
            </ElFormItem>
            <ElFormItem v-if="ruleForm.taskType === '2'" label="分享语">
              <el-input v-model="ruleForm.templateIds" type="textarea" placeholder="请输入分享语" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="12">
            <ElFormItem label="任务描述" prop="taskDesp">
              <el-input v-model="ruleForm.taskDesp" type="textarea" placeholder="请输入任务描述" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="12">
            <ElFormItem label="奖励描述" prop="awardDesp">
              <el-input v-model="ruleForm.awardDesp" type="textarea" placeholder="请输入奖励描述" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="12">
            <ElFormItem label="任务图标" prop="pic">
              <ImageUpload
                :size="5" :url="ruleForm.pic" @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'pic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.taskType === '3' || ruleForm.taskType === '2'" :md="12">
            <ElFormItem :label="ruleForm.taskType === '3' ? '企微二维码' : '分享图'">
              <ImageUpload
                :size="5" :url="ruleForm.qvcodePic" @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'qvcodePic')"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

  <style lang="scss" scoped>
  :deep(.el-date-editor) {
    width: 100%;
  }

  .tag {
    max-width: 300px;
    color: red;
  }
  </style>
